package com.sftz.modules.minapp.seriesCouresDetail.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.log.Log;
import org.nutz.log.Logs;

import com.sftz.assets.entities.CourseEntity;
import com.sftz.assets.entities.InstitutionCoursesEntity;
import com.sftz.assets.entities.InstitutionEntity;
import com.sftz.assets.entities.SeriesCoursesEntity;
import com.sftz.assets.entities.StudentMajorEntity;
import com.sftz.assets.entities.TOrderEntity;
import com.sftz.assets.entities.UserCoursesltEntity;
import com.sftz.assets.entities.UserProductEntity;
import com.sftz.assets.entities.UserScoreRelationshipEntity;
import com.sftz.assets.enums.CourseStateEnum;
import com.sftz.assets.enums.CourseTypeEnum;
import com.sftz.assets.enums.OrderStatusEnum;
import com.sftz.assets.enums.OrderTypeEnum;
import com.sftz.assets.enums.YesOrNoEnum;
import com.sftz.modules.minapp.seriesCouresDetail.dto.CourTypeDto;
import com.sftz.modules.minapp.seriesCouresDetail.dto.Course;
import com.sftz.modules.minapp.seriesCouresDetail.dto.InstituSerCourDto;
import com.uxuexi.core.common.util.DateTimeUtil;
import com.uxuexi.core.common.util.DateUtil;
import com.uxuexi.core.common.util.Util;
import com.uxuexi.core.db.util.DbSqlUtil;
import com.uxuexi.core.web.base.service.BaseService;

@IocBean
public class SerirsecoursedetailViewService extends BaseService<SeriesCoursesEntity> {
	private static final Log log = Logs.get();

	private static final Integer buyFlag = 1;

	private static final Integer noBuyFlag = -1;

	public Object serCouDetail(Integer id, Integer userId) {

		Map<String, Object> map = new HashMap<String, Object>();

		//查询头部学院名称、专业详情
		Sql serCouDetailSql = Sqls.create(sqlManager.get("minapp_seriesCourDetail_head"));
		serCouDetailSql.setParam("id", id);
		InstituSerCourDto serCourInfo = DbSqlUtil.fetchEntity(dbDao, InstituSerCourDto.class, serCouDetailSql);
		map.put("serCourInfo", serCourInfo);

		//统计专业课程分类数量
		Sql courseCountSql = Sqls.create(sqlManager.get("minapp_seriesCourDetail_courseCount"));
		courseCountSql.setParam("id", id);
		courseCountSql.setParam("courseState", CourseStateEnum.PUBLISHED.intKey());
		courseCountSql.setParam("isDelete", YesOrNoEnum.NO.intKey());
		List<CourTypeDto> courseCount = DbSqlUtil.query(dbDao, CourTypeDto.class, courseCountSql);

		//查询专业课程分类下的课程
		Sql courseSql = Sqls.create(sqlManager.get("minapp_seriesCourDetail_course"));
		courseSql.setParam("id", id);
		courseSql.setParam("courseState", CourseStateEnum.PUBLISHED.intKey());
		List<Course> course = DbSqlUtil.query(dbDao, Course.class, courseSql);

		//循环进行一对多的赋值（分类-课程列表）
		for (CourTypeDto courTypeDto : courseCount) {

			List<Course> list = new ArrayList<Course>();
			for (Course course2 : course) {
				if (courTypeDto.getClassName().equals(course2.getClassName())) {
					list.add(course2);
				}
				courTypeDto.setList(list);
			}
			if (courseCount.size() == 1 && courTypeDto.getIsTypeEmpty() == 1) {
				courTypeDto.setClassName("");
			}
		}
		//统计专业课程分类数量及专业课程分类
		map.put("courseCount", courseCount);

		//判断用户是否已购买该专业	
		Integer buyOrNoBuyFlag = seriousCourseBuyOrNot(userId, id);
		map.put("buyOrNoBuyFlag", buyOrNoBuyFlag);
		return map;

	}

	//判断用户是否已购买该专业	
	public Integer seriousCourseBuyOrNot(Integer userId, Integer productId) {
		Integer buyOrNoBuyFlag = noBuyFlag;
		if (!Util.isEmpty(userId)) {
			UserProductEntity user = dbDao.fetch(
					UserProductEntity.class,
					Cnd.where("productId", "=", productId).and("userId", "=", userId)
							.and("orderType", "=", OrderTypeEnum.COURSESERIES.intKey()));
			if (!Util.isEmpty(user)) {
				buyOrNoBuyFlag = buyFlag;
			}
		}
		return buyOrNoBuyFlag;
	}

	//免费系列课程添加报名人数
	public void addCourseStudyCountNum(Integer productId) {
		Sql sql = Sqls.create(sqlManager.get("minapp_coursedetails_addCourseStudyCountNum"));
		sql.params().set("id", productId);
		dbDao.execute(sql);
	}

	//免费系列课程添加报名人数
	public void addNum(Integer productId) {
		Sql sql = Sqls.create(sqlManager.get("minapp_seriesCourseDetail_addNum"));
		sql.setParam("id", productId);
		dbDao.execute(sql);
		//根据系列id查机构id
		SeriesCoursesEntity fetch = dbDao.fetch(SeriesCoursesEntity.class, Cnd.where("id", "=", productId));
		//查询机构报名人数为null则置为0
		InstitutionEntity ins = dbDao.fetch(InstitutionEntity.class, Cnd.where("id", "=", fetch.getInsititutionId()));
		if (Util.isEmpty(ins.getSignCount())) {
			dbDao.update(InstitutionEntity.class, Chain.make("signCount", 0), Cnd.where("id", "=", ins.getId()));
		}
		//修改学院报名人数
		Sql sqlins = Sqls.create(sqlManager.get("minapp_institution_addNum"));
		sqlins.setParam("id", fetch.getInsititutionId());
		dbDao.execute(sqlins);
	}

	//免费（系列课程/课程）报名添加用户商品表及选课、学生表数据添加
	public Integer addUserProduct(Integer productId, Integer userId, Integer courseTyp) throws ParseException {
		if (Util.isEmpty(productId)) {
			return null;
		} else if (Util.isEmpty(userId)) {
			return null;
		} else if (Util.isEmpty(courseTyp)) {
			return null;
		}

		//添加时间
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = df.parse(df.format(new Date()));

		//添加用户商品表
		UserProductEntity userProductEntity = new UserProductEntity();
		userProductEntity.setPurchaseDate(date);
		userProductEntity.setUserId(userId);
		userProductEntity.setProductId(productId);
		userProductEntity.setOrderType(courseTyp);
		userProductEntity = dbDao.insert(userProductEntity);
		int userProductId = userProductEntity.getId();

		//选课表及学生表数据添加
		//当前时间
		Date nowDate = DateTimeUtil.nowDate();
		String createTime = DateUtil.Date2String(nowDate);
		StudentMajorEntity stu = new StudentMajorEntity();
		UserCoursesltEntity userCourse = new UserCoursesltEntity();
		//购买的是系列课程
		if (courseTyp == OrderTypeEnum.COURSESERIES.intKey()) {
			//添加到选课信息表里--haozhenbin
			UserCoursesltEntity userCour = dbDao.fetch(UserCoursesltEntity.class,
					Cnd.where("userId", "=", userId).and("seriesId", "=", userProductEntity.getProductId()));
			if (Util.isEmpty(userCour) && !Util.isEmpty(userProductEntity)) {
				userCourse.setUserId(userProductEntity.getUserId());
				userCourse.setSeriesId(userProductEntity.getProductId());
				userCourse.setCheckStatus(YesOrNoEnum.NO.intKey());
				dbDao.insert(userCourse);
			}
			//添加进学生表里 
			//查询当前专业属于哪个机构
			SeriesCoursesEntity fetch = dbDao.fetch(SeriesCoursesEntity.class, Cnd.where("id", "=", productId));
			if (!Util.isEmpty(fetch)) {
				Integer insititutionId = fetch.getInsititutionId();
				//---查询该用户是否在学生表中存在并且购买过该专业
				Sql queryStudent = Sqls.create(sqlManager.get("minapp_seriesCourseDetail_student_is_or_no"));
				queryStudent.setParam("majorId", productId);
				queryStudent.setParam("userId", userId);
				queryStudent.setParam("institutionId", insititutionId);
				List<StudentMajorEntity> serCour = DbSqlUtil.query(dbDao, StudentMajorEntity.class, queryStudent);
				//没有购买过
				if (Util.isEmpty(serCour)) {
					stu.setMajorId(productId);
					stu.setUserId(userId);
					stu.setInstitutionId(insititutionId);
					stu.setCreateTime(createTime);
					stu = dbDao.insert(stu);
				}
			}
		}
		//购买的是单个课程
		if (courseTyp == OrderTypeEnum.COURSE.intKey()) {
			//查询当前课程属于个人课程还是机构课程
			CourseEntity course = dbDao.fetch(CourseEntity.class, Cnd.where("id", "=", productId));
			//机构课程
			if (course.getCourseType() == CourseTypeEnum.INSTITUTIONCOURSE.intKey()) {
				//查询当前课程属于哪个机构
				InstitutionCoursesEntity insCourse = dbDao.fetch(InstitutionCoursesEntity.class,
						Cnd.where("courseId", "=", productId));
				//查询当前课程是否被该用户曾经购买过
				Sql stuCourSql = Sqls.create(sqlManager.get("minapp_seriesCourDetail_buy_ins_single_course"));
				stuCourSql.setParam("courseId", productId);
				stuCourSql.setParam("institutionId", insCourse.getInstitutionId());
				stuCourSql.setParam("userId", userId);
				List<StudentMajorEntity> serCour = DbSqlUtil.query(dbDao, StudentMajorEntity.class, stuCourSql);
				//--------当前课程之前未购买过
				if (Util.isEmpty(serCour)) {
					//添加学生表
					stu.setInstitutionId(insCourse.getInstitutionId());
					stu.setUserId(userId);
					stu.setCreateTime(createTime);
					stu = dbDao.insert(stu);
					//将课程添加进学分表
					UserScoreRelationshipEntity userScore = new UserScoreRelationshipEntity();
					userScore.setStudentId(stu.getId());
					userScore.setCourseId(productId);
					userScore = dbDao.insert(userScore);
				}
			} else {
				//个人课程
				//查询当前用户是否在学生表存在
				Sql queryS = Sqls.create(sqlManager.get("minapp_seriesCourDetail_query_user_stu_course"));
				queryS.setCondition(Cnd.where("ur.courseId", "=", productId).and("sm.userId", "=", userId));
				StudentMajorEntity fetchEntity = DbSqlUtil.fetchEntity(dbDao, StudentMajorEntity.class, queryS);
				//未购买过
				if (Util.isEmpty(fetchEntity)) {
					stu.setUserId(userId);
					stu.setCreateTime(createTime);
					stu = dbDao.insert(stu);

					UserScoreRelationshipEntity userScore = new UserScoreRelationshipEntity();
					userScore.setStudentId(stu.getId());
					userScore.setCourseId(productId);
					userScore = dbDao.insert(userScore);
				}

			}
		}
		return userProductId;
	}

	/**
	 * 查询当前是否有24小时之内未支付的此订单
	 */
	public Object serOrderDetail(Integer id, Integer userId) {
		//查询该客户该专业所有订单
		Sql studentS = Sqls.create(sqlManager.get("minapp_seriesCourDetail_24hCanUseOrder"));
		Cnd cnd = Cnd.NEW();
		cnd.and("userId", "=", userId).and("t.orderType", "=", OrderTypeEnum.COURSESERIES.intKey())
				.and("t.productId", "=", id).and("t.orderState", "=", OrderStatusEnum.WAIT_PAY.intKey())
				.or("t.orderState", "=", OrderStatusEnum.CANCEL.intKey()).desc("t.orderCreateTime");

		studentS.setCondition(cnd);
		List<TOrderEntity> order = DbSqlUtil.query(dbDao, TOrderEntity.class, studentS);
		TOrderEntity ord = new TOrderEntity();
		//判断24h内未失效的最新订单
		if (!Util.isEmpty(order)) {
			for (TOrderEntity o : order) {
				Date orderCreateTime = o.getOrderCreateTime();
				Calendar calendar = Calendar.getInstance();
				calendar.setTime(orderCreateTime);
				calendar.add(calendar.HOUR, 24);
				Date time = calendar.getTime();
				Date dateNow = new Date();
				if (dateNow.before(time)) {
					ord = o;
					break;
				}
			}
		}

		return ord;

	}

}